package handlers

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"zong-microservice/app/models"
	"zong-microservice/app/services/user/proto"
	"zong-microservice/pkg/auth"
	"zong-microservice/pkg/cache"
	"zong-microservice/pkg/password"
)

type UserHandler struct {
	model models.User
}

// CreateUser 创建用户
func (handler *UserHandler) CreateUser(context context.Context, req *proto.CreateUserRequest, resp *proto.CreateUserResponse) error {
	if _, err := handler.model.GetByUsername(req.Username); err == nil {
		resp.Code = 1
		resp.Message = "用户已存在"
		return err
	}

	handler.model.Username = req.Username
	handler.model.Name = req.Name
	handler.model.Phone = req.Phone
	handler.model.Password = password.Hash(req.Password)
	*handler.model.Sex = int(req.Sex)
	*handler.model.Status = int(req.Status)

	if err := handler.model.Create(); err != nil {
		resp.Code = 1
		resp.Message = err.Error()
		return err
	} else {
		user, err := json.Marshal(handler.model)
		if err != nil {
			resp.Code = 1
			resp.Message = err.Error()
			return err
		}
		resp.Data = string(user)
		resp.Code = 0
		resp.Message = "success"
		return nil
	}
}

// UpdateUser 更新用户
func (handler *UserHandler) UpdateUser(context context.Context, req *proto.UpdateUserRequest, resp *proto.UpdateUserResponse) error {
	if _, err := handler.model.Get(req.Id); err != nil {
		resp.Code = 1
		resp.Message = "用户不存在"
		return err
	}

	handler.model.ID = req.Id
	handler.model.Name = req.Name
	handler.model.Phone = req.Phone
	*handler.model.Sex = int(req.Sex)
	*handler.model.Status = int(req.Status)

	if err := handler.model.Update(); err != nil {
		resp.Code = 1
		resp.Message = err.Error()
		return err
	} else {
		resp.Code = 0
		resp.Message = "success"
		return nil
	}
}

// DeleteUser 删除用户
func (handler *UserHandler) DeleteUser(context context.Context, req *proto.DeleteUserRequest, resp *proto.DeleteUserResponse) error {
	if _, err := handler.model.Get(req.Id); err != nil {
		resp.Code = 1
		resp.Message = "用户不存在"
		return err
	}

	handler.model.ID = req.Id

	if err := handler.model.Delete(); err != nil {
		resp.Code = 1
		resp.Message = err.Error()
		return err
	} else {
		resp.Code = 0
		resp.Message = "success"
		return nil
	}
}

// UserList 用户列表
func (handler UserHandler) UserList(context context.Context, req *proto.UserListRequest, resp *proto.UserListResponse) error {
	if req.Id > 0 {
		if one, err := handler.model.Get(req.Id); err != nil {
			resp.Code = 1
			resp.Message = err.Error()
			return err
		} else {
			list, err := json.Marshal(one)
			if err != nil {
				resp.Code = 1
				resp.Message = err.Error()
				return err
			}
			resp.Data = string(list)
			resp.Code = 0
			resp.Message = "success"
			return nil
		}
	} else {
		cond := map[string]interface{}{
			"username =": req.Username,
		}
		if all, err := handler.model.GetRpcAllPaging(cond, int(req.PerPage), req.Page, req.BaseUrl); err != nil {
			resp.Code = 1
			resp.Message = err.Error()
			return err
		} else {
			list, err := json.Marshal(all)
			if err != nil {
				resp.Code = 1
				resp.Message = err.Error()
				return err
			}
			resp.Data = string(list)
			resp.Code = 0
			resp.Message = "success"
			return nil
		}
	}
}

// Me 用户当前信息
func (handler UserHandler) Me(context context.Context, req *proto.MeRequest, resp *proto.MeResponse) error {
	authorization := req.AccessToken
	token, _ := auth.ParseToken(strings.Fields(authorization)[1])

	if !cache.Exists("UserCache_" + token.Id) {
		resp.Code = 1
		resp.Message = "用户不存在"
		return errors.New("User does not exist.")
	} else {
		userCache := cache.Get("UserCache_" + token.Id)
		userData := fmt.Sprintf("%v", userCache) // interface{} 转 string

		resp.Data = userData
		resp.Code = 0
		resp.Message = "success"
		return nil
	}
}

// UpdateUserPassword 用户修改密码
func (handler *UserHandler) UpdateUserPassword(context context.Context, req *proto.UpdateUserPasswordRequest, resp *proto.UpdateUserPasswordResponse) error {
	if u, err := handler.model.GetByUsername(req.Username); err != nil {
		resp.Code = 1
		resp.Message = err.Error()
		return err
	} else {
		if ok := u.ComparePassword(req.Password); !ok {
			resp.Code = 1
			resp.Message = "用户密码错误"
			return errors.New("User password error.")
		}

		if err = u.ResetPassword(password.Hash(req.PasswordComfirm)); err != nil {
			resp.Code = 1
			resp.Message = err.Error()
			return err
		} else {
			user, err := json.Marshal(u)
			if err != nil {
				resp.Code = 1
				resp.Message = err.Error()
				return err
			}
			resp.Data = string(user)
			resp.Code = 0
			resp.Message = "success"
			return nil
		}
	}
}

// DoRegister 用户注册
func (handler *UserHandler) DoRegister(context context.Context, req *proto.DoRegisterRequest, resp *proto.DoRegisterResponse) error {
	if _, err := handler.model.GetByUsername(req.Username); err == nil {
		resp.Code = 1
		resp.Message = "用户已存在"
		return err
	}

	handler.model.Username = req.Username
	handler.model.Name = req.Name
	handler.model.Phone = req.Phone
	handler.model.Password = password.Hash(req.Password)
	*handler.model.Sex = int(req.Sex)
	*handler.model.Status = int(req.Status)

	if err := handler.model.Create(); err != nil {
		resp.Code = 1
		resp.Message = err.Error()
		return err
	} else {
		user, err := json.Marshal(handler.model)
		if err != nil {
			resp.Code = 1
			resp.Message = err.Error()
			return err
		}
		resp.Data = string(user)
		resp.Code = 0
		resp.Message = "success"
		return nil
	}
}
